<script setup lang="ts">
import Editbom from "./components/editbom.vue";
import { getRecipePlan, getRecipePlanRevoke, PlanRecipeRevokeBatchApi } from "@/api/Recipe";
import { GetDishTypeattributeScope } from "@/api/Dashmana";
import { getTenantSubList } from '@/api/System'

import dayjs from "dayjs"
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
const RecipeTableData = ref([]);

const recipeColumn = reactive([
  {
    key: "tenantName",
    width: 150,
    name: "制作单位 ",
  },
  {
    key: "recipePlanCode",
    width: 150,
    name: "菜谱计划单号 ",
  },
  {
    key: "recipePlanName",
    width: 200,
    name: "菜谱名称",
  },
  {
    slot: "planDate",
    name: "菜谱计划日期",
    width: 140,
  },
  {
    key: "useScopeName",
    name: "供餐模式",
  },
  {
    slot: "examineStatus",
    name: "审核状态",
    width: 100
  },

  {
    key: "createTime",
    name: "创建时间",
    width: 130
  },

  {
    slot: "operate",
    name: "操作",
    width: 100,
    fixed: "right",
  },
]);
const treeProps = { children: "children", label: "skuClassName" };
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 15,
});
const pages = ref(pageInit());
const examineStatusObj = {
  // '0uncommitted': {
  //   name: '待提交',
  //   color: ''
  // },
  '1wait_examine': {
    name: '待审核',
    color: '#bfbfbf'
  },
  '3pass': {
    name: '已通过',
    color: '#09B562'
  },
  '2fail': {
    name: '未通过',
    color: '#F52F3E'
  }
}
const onPagesChange = () => {
  getRecipePlanApi();
};



const staOrigin = () => [
  { label: "全部", val: null, checked: true },
  // { label: "待提交", val: '0uncommitted', checked: false },
  { label: "待审核", val: '1wait_examine', checked: false },
  { label: "已通过", val: '3pass', checked: false },
  { label: "未通过", val: '2fail', checked: false },
];

const matchList = ref([]);
const staList = ref(staOrigin());

const formOrigin = () => ({
  planDateBegin: dayjs().startOf('week').format('YYYY-MM-DD'),
  planDateEnd: dayjs().endOf('week').format('YYYY-MM-DD'),
  recipePlanName: null,
  recipePlanCode: null,
  useScopeAttributeId: null,
  examineStatus: null,
  tenantId: ''
});
const EditbomRef = ref(null)
const matchPopRef = ref(null)

const searchForm = ref(formOrigin());
const planDateRang = ref([searchForm.value.planDateBegin, searchForm.value.planDateEnd])
const dateChange = () => {
  searchForm.value.planDateBegin = dayjs(planDateRang.value[0]).format('YYYY-MM-DD')
  searchForm.value.planDateEnd = dayjs(planDateRang.value[1]).format('YYYY-MM-DD')
  console.log(searchForm);

}
const EditbomShow = ref(true)
const subList = ref([])
// 获取制作单位列表
const getTenantSubListApi = () => {
  return new Promise<void>((resolve, reject) => {
    getTenantSubList().then(res => {
      if (res.code == 2000) {
        subList.value = res.data
      }
    })
  })
}
const onit = () => {
  getRecipePlanApi()
  GetDishTypeattributeScopeFn()
  getTenantSubListApi()
}
const searchFn = () => {
  getRecipePlanApi();

};
const loading = ref(false)
const resetFn = () => {
  searchForm.value = formOrigin();
  staList.value = staOrigin();
  planDateRang.value = [searchForm.value.planDateBegin, searchForm.value.planDateEnd]
  getRecipePlanApi();
};
// 编辑查看
const editRecipe = (row = '', item) => {

  if (['编辑', '查看', '新增'].includes(item)) {
    EditbomRef.value.onShow(row, item)
  }

}
const changeCheck = (event, type) => {

  if (type == 'match') {
    searchForm.value.useScopeAttributeId = event.dishAttributeValueId
  } else if (type == 'status') {
    searchForm.value.examineStatus = event.val
  }
  getRecipePlanApi();
}
// 撤销
const onRevoke = ({ recipePlanId }) => {
  getRecipePlanRevokeApi(recipePlanId)
}
// 选择节点
const skuClassCode = ref("");
const nodeClick = ({ curNode }) => {
  skuClassCode.value = curNode.skuClassCode
  getRecipePlanApi()
};
const onRefresh = () => {
  getRecipePlanApi()
}
// 获取食谱信息列表
const getRecipePlanApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    let { currentPage, pageSize } = { ...pages.value };
    let params = {
      currentPage,
      pageSize,
      ...searchForm.value,
    };
    getRecipePlan(params).then((res) => {
      loading.value = false
      if (res.code == 2000) {
        RecipeTableData.value = res.data.records;
        pages.value.total = res.data.total;
      }
    });
  });
};
// 获取菜谱模式接口
const GetDishTypeattributeScopeFn = () => {
  return new Promise(resolve => {
    GetDishTypeattributeScope({
      currentPage: 1,
      pageSize: 100,
      sortingFields: [
        {
          field: "",
          order: ""
        }
      ],
      dishAttributeType: "scope"
    }).then(res => {
      if (res.code == 2000) {
        matchList.value = [{
          dishAttributeValue: '全部',
          dishAttributeId: null,
          checked: true
        }, ...res.data]
      }
    })
  })
}

// 撤销审核接口 
const getRecipePlanRevokeApi = (recipePlanId) => {
  loading.value = true
  return new Promise((resolve, reject) => {

    getRecipePlanRevoke({ recipePlanId }).then((res) => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: `撤销审核成功`
        })
      }
      getRecipePlanApi()
    });
  });
};
let treeH = ref(null);
const BatchBtnFn = () => {
  if (!batchList.value || batchList.value.length == 0) return createMessage({
    message: '请选择需要操作的数据！',
    type: 'error'
  })
  let arr: any = []
  batchList.value.map((el: any) => {
    arr.push(el.recipePlanId)
  })
  PlanRecipeRevokeBatchApi({
    recipePlanIdList: arr
  }).then(res => {
    if (res.code == 2000) {
      createMessage({
        message: '批量撤销成功'
      })
      getRecipePlanApi()
    }
  })
}
const batchList = ref([] as any)
const handleSelectionChange = (val: any) => {
  batchList.value = val;
}
onMounted(() => {
  onit()
})
</script>
<template>
  <div class="app-container flex flex-col">
    <!-- 查询区 -->
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="searchForm" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="菜谱日期：">
          <pb-date-picker v-model="planDateRang" placeholder="请输入菜谱日期" @change="dateChange"></pb-date-picker>
        </el-form-item>
        <el-form-item label="菜谱名称：">
          <pb-input v-model="searchForm.recipePlanName" placeholder="请输入菜谱名称"></pb-input>
        </el-form-item>

        <el-form-item label="菜谱计划单号：">
          <pb-input v-model="searchForm.recipePlanCode" placeholder="请输入菜谱计划单号 "></pb-input>
        </el-form-item>
        <el-form-item label="制作单位：">
          <pb-select v-model="searchForm.tenantId" :options="subList" placeholder="请选择单位" keys="tenantId"
            label="tenantName" @change="searchFn" width="200"></pb-select>
        </el-form-item>
        <el-form-item label="审核状态：">
          <pb-check :list="staList" @change="changeCheck($event, 'status')"></pb-check>
        </el-form-item>
        <el-form-item label="供餐模式：">
          <pb-check :list="matchList" :defaultProps="{ label: 'dishAttributeValue' }"
            @change="changeCheck($event, 'match')"></pb-check>
        </el-form-item>
      </el-form>
    </searchCard>

    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <div class="content-box">
          <ContentOperation
            style="justify-content: left;margin-left: 12px;align-items: center;color: rgba(0, 0, 0, 0.55)">
            <span class="m-r3">当前选中 {{ batchList && batchList.length > 0 ? batchList.length : 0 }} 行</span>
            <!-- <div class="m-r4">
              <PopconfirmButton @confirm="BatchBtnFn('1')" text="批量审核">
              </PopconfirmButton>
            </div> -->
            <div>
              <PopconfirmButton @confirm="BatchBtnFn('2')" text=" 批量撤销">
              </PopconfirmButton>
            </div>
          </ContentOperation>
          <div class="table-box ">
            <div class="table-right ">
              <pb-table :column="recipeColumn" :loading="loading" :tableData="RecipeTableData"
                :bottomElement="['pb-page']" @SelectionChange="handleSelectionChange($event)" :selectionShow="true">
                <template #examineStatus="{ row }">
                  <div class="flex items-center">
                    <span class="icon" :style="{ background: examineStatusObj[row.examineStatus]?.color }"></span>
                    <div>{{ examineStatusObj[row.examineStatus]?.name }}</div>
                  </div>
                </template>
                <template #isPublish="{ row }">
                  <div class="flex items-center">
                    <span class="icon" :style="{ background: row.isPublish ? '#09B562' : '#F52F3E' }"></span>
                    <div>{{ row.isPublish ? '已发布' : '未发布' }}</div>
                  </div>

                </template>
                <template #planDate="{ row }">
                  <div>{{ row.planDateBegin }} - {{ row.planDateEnd }}</div>
                </template>
                <template #operate="{ row }">
                  <div class="flex">
                    <div v-if="row.examineStatus == '3pass'" v-hasPerm="'center:recipeAudit:revoke'">
                      <PopconfirmButton text="撤销" @confirm="onRevoke(row)">
                      </PopconfirmButton>
                      <p class=" divider mr-2 ml-2">
                      </p>
                    </div>

                    <pb-button size="small" text @click="editRecipe(row, '查看')"
                      v-hasPerm="'center:recipeAudit:detail'">查看</pb-button>
                  </div>

                </template>
              </pb-table>
              <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
                @onChange="onPagesChange" :total="pages.total"></pb-pagination>
            </div>
          </div>
        </div>
      </pb-card>
    </div>
    <!-- 添加修改弹窗 -->
    <Editbom :matchList="matchList" ref="EditbomRef" :isVisible="EditbomShow" @onRefresh="onRefresh">
    </Editbom>

  </div>
</template>

<style lang="scss" scoped>
.content-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-box {
  flex: 1;
  overflow: hidden;

  .table-right {
    /* width: 84%; */
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
}

.icon {
  width: 6px;
  height: 6px;
  background-color: #09B562;
  border-radius: 50%;
  margin-right: 3px;
}
</style>